<?php /** @noinspection ALL */
/** @noinspection PhpUndefinedClassInspection */

/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020-6-10 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace api\modules\backend\controllers;

use Yii;
use api\controllers\AuthAdminController;

/**
 * 后台权限接口 controller for the `backend` module
 * 权限名称格式：控制器名+动作名(不含前缀action)
 */
class PermissionController extends AuthAdminController
{
    /**
     * 获取列表
     * @return mixed
     */
    public function actionList()
    {
        $auth = Yii::$app->getAuthManager();
        $permis =  $auth->getPermissions();
        $data = [];
        $i = 1;
        foreach ($permis as $key => $item) {
            $data[] = ['id' => $i++, 'name' => $item->name, 'rule_name' => $item->ruleName ? $item->ruleName : '', 'description' => $item->description];
        }
        return Yii::$app->api->success(['items' => $data]);
    }

    /**
     * 创建权限
     * @return mixed
     * @throws \Exception
     */
    public function actionCreate()
    {
        $auth = Yii::$app->getAuthManager();
        $name = trim(Yii::$app->getRequest()->post('name'));
        $desc = trim(Yii::$app->getRequest()->post('description'));
        $rule = $auth->createPermission($name);
        $rule->description = $desc;
        if ($name && $auth->add($rule)) {
            return Yii::$app->api->success();
        }
        return Yii::$app->api->error();
    }

    /**
     * 更新角色
     * @return mixed
     * @throws \Exception
     */
    public function actionUpdate()
    {
        $auth = Yii::$app->getAuthManager();
        $name = trim(Yii::$app->getRequest()->post('name'));
        $newName = trim(Yii::$app->getRequest()->post('new_name'));
        $desc = trim(Yii::$app->getRequest()->post('description'));
        try {
            $rule = $auth->getPermission($name);
            $rule->name = $newName ? $newName : $rule->name;
            $rule->description = $desc;
            $auth->update($name, $rule);
            return Yii::$app->api->success('更新成功');
        } catch (\Exception $e) {
            return Yii::$app->api->error($e->getMessage());
        }
        return Yii::$app->api->error('更新失败');
    }
}
